//
//  reconmendAlertView.m
//  SoundPill
//
//  Created by 宋旭东 on 16/4/1.
//  Copyright © 2016年 宋旭东. All rights reserved.
//

#import "reconmendAlertView.h"
#import "RGCardViewLayout.h"
#import "reconmendCell.h"
#import "AppDelegate.h"
#import "AFNetworking.h"
#import "UIImageView+WebCache.h"
#import "UIImage+thumbImage.h"
#import "UIViewExt.h"
#import "DownSheetModel.h"
#import "DownSheet.h"
#import "WXApi.h"
#import "WeiboSDK.h"
@interface reconmendAlertView ()<DownSheetDelegate>
{
    BOOL isSignClicked;
    int distans;
    float avatarWidth;
}
@property (strong, nonatomic) NSArray *dateArray;
@property (strong, nonatomic) NSString *shareWorkTitle;
@property (strong, nonatomic) NSString *shareUserName;
@property (strong, nonatomic) NSString *shareWorkId;
@property (strong, nonatomic) NSString *shareCoverStr;
@end

@implementation reconmendAlertView


- (instancetype)initWithFrame:(CGRect)frame isSigned:(BOOL)isSigned
{
    self = [super initWithFrame:frame];
    if (self) {
        if ([UIScreen mainScreen].bounds.size.width == 320) {
            distans = 5;
            avatarWidth = 15;
        } else {
            distans = 10;
            avatarWidth = 20;
        }
        self.isSigned = isSigned;
        self.userInteractionEnabled = YES;
        self.reconmendArray = [[NSMutableArray alloc] init];
        self.dateArray = [NSArray arrayWithObjects:@"一",@"二",@"三",@"四",
            @"五",@"六",@"七",@"八",@"九",@"十",
            @"十\n一",@"十\n二",@"十\n三",@"十\n四",
            @"十\n五",@"十\n六",@"十\n七",@"十\n八",
            @"十\n九",@"二\n十",@"二\n十\n一",
            @"二\n十\n二",@"二\n十\n三",@"二\n十\n四",@"二\n十\n五",@"二\n十\n六",
            @"二\n十\n七",@"二\n十\n八",@"二\n十\n九",@"三\n十",@"三\n十\n一", nil];
        [self AFNetworking:1];
        [self createSubview];
    }
    return self;
}
- (void)AFNetworking:(int)pag
{
    //    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    NSString *url = [NSString stringWithFormat:@"http://123.57.1.143/api/work/dm?p=%d", pag];
    NSString *requestheader = [NSString stringWithFormat:@"Token %@:%@",[[NSUserDefaults standardUserDefaults] valueForKey:@"uid"], [[NSUserDefaults standardUserDefaults] valueForKey:@"token"]];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer setValue:requestheader forHTTPHeaderField:@"authorization"];
    [manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self reloadDataWithResponseObject:responseObject pag:pag];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
- (void)reloadDataWithResponseObject:(id)responseObject pag:(int)pag
{
    NSDictionary *bigDic = responseObject;
    NSArray *dic = [bigDic valueForKey:@"data"];
    for (int i = 0; i < dic.count; i++) {
        NSDictionary *dict = dic[i];
//        NSLog(@"%@",dict);
//    for (NSDictionary *dict in dic) {
        plaza_viewModel *model = [[plaza_viewModel alloc] init];
        model.CinemeID = [dict objectForKey:@"id"];
        //
        model.UserID = [dict objectForKey:@"uid"];
        //头像
        model.headImageURL = [[dict valueForKey:@"user"] valueForKey:@"avatar"];
        //NSLog(@"--%@",[item objectForKey:@"avatar"]);
        //名字
        model.personName = [[dict valueForKey:@"user"] valueForKey:@"username"];
        //标签
        model.signArray =  [dict objectForKey:@"tags"];
        //上传日期
        NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
        
            NSDateComponents *comps = nil;
        
           comps = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:[NSDate date]];
        
            NSDateComponents *adcomps = [[NSDateComponents alloc] init];
            [adcomps setDay:-i];
        
            NSDate *newdate = [calendar dateByAddingComponents:adcomps toDate:[NSDate date] options:0];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"YYYYMMdd"];
        NSString *dateString = [dateFormatter stringFromDate:newdate];
        model.releaseDate = dateString;//[dict objectForKey:@"created_at"];
        //标题
        model.title = [dict objectForKey:@"title"];
        //作品预览图
        model.worksImageURL = [dict objectForKey:@"cover"];
        //播放次数
        model.playTimes = [dict objectForKey:@"play_count"];
        //点按数量（心）
        model.heartCount = [dict objectForKey:@"love_count"];
        model.reason = [dict objectForKey:@"dmshow"];
//        model.dmshow = [dict objectForKey:@"dmshow"];
        //时长
        model.duration = [dict objectForKey:@"duration"];
        if([dict objectForKey:@"liked"]){
            // NSLog(@"%@",[item objectForKey:@"liked"]);
            model.isLike = [[dict objectForKey:@"liked"] boolValue];
        }
        [self.reconmendArray addObject:model];
    }
    
    [_collectionView reloadData];
    
}
- (void)createSubview
{
    self.dismiss = [UIButton buttonWithType:UIButtonTypeCustom];
    _dismiss.frame = self.bounds;
//    _dismiss.backgroundColor = [UIColor grayColor];
    [self addSubview:_dismiss];
    
    RGCardViewLayout *layout = [[RGCardViewLayout alloc] init];
    if (_isSigned == YES) {
        self.collectionView=[[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.width * 0.8 *1.45) collectionViewLayout:layout];
    } else {
        self.collectionView=[[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.width * 0.8 *1.65) collectionViewLayout:layout];
    }
//    _collectionView.backgroundColor = [UIColor redColor];
    _collectionView.center = self.center;
    self.collectionView.dataSource=self;
    self.collectionView.delegate=self;
    [self.collectionView setBackgroundColor:[UIColor clearColor]];
    self.collectionView.pagingEnabled = YES;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    [self.collectionView registerClass:[reconmendCell class] forCellWithReuseIdentifier:@"UICollectionViewCell"];
    [self addSubview:self.collectionView];
    
}
#pragma mark -- UICollectionViewDataSource

//定义展示的UICollectionViewCell的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 1;
}

//定义展示的Section的个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return _reconmendArray.count;
}

//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * CellIdentifier = @"UICollectionViewCell";
    reconmendCell * cell = (reconmendCell *)[collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    plaza_viewModel *model = _reconmendArray[indexPath.section];
   
    if (cell) {
        cell.model = model;
        cell.cover.frame = CGRectMake(23, 23, cell.width - 46, cell.width-46);
        [cell.cover setImageWithURL:[NSURL URLWithString:model.worksImageURL] placeholderImage:[UIImage imageNamed:@"plazz_placeholderImage"]];
        
        cell.playBtn.frame = CGRectMake(cell.cover.left, cell.cover.top, cell.cover.width, cell.cover.height);
        [cell.playBtn setImage:[UIImage imageNamed:@"Play_playButton"] forState:UIControlStateNormal];
        
        NSString *month =[model.releaseDate substringWithRange:NSMakeRange(4, 2)];
        NSString *day = [model.releaseDate substringWithRange:NSMakeRange(6, 2)];
        NSString *dateStr = [NSString stringWithFormat:@"%@\n月\n%@\n日",_dateArray[month.intValue - 1],_dateArray[day.intValue - 1]];
        CGSize dateSize = [self boundingRectWithSize:CGSizeMake(40, 200) text:dateStr font:cell.workDate.font];
        cell.workDate.frame = CGRectMake(0, 0, dateSize.width + 20, dateSize.height + 20);
        cell.workDate.text = dateStr;
        cell.workDate.center = CGPointMake(cell.workDate.center.x, cell.cover.center.y);
        
//        NSString *tagStr;
//        if (model.signArray.count > 3) {
//            NSArray *array = [model.signArray subarrayWithRange:NSMakeRange(0, 3)];
//            tagStr = [array componentsJoinedByString:@"，"];
//        } else {
//            tagStr = [model.signArray componentsJoinedByString:@"，"];
//        }
//        cell.tagLabel.frame = CGRectMake(cell.cover.left + 15, cell.width - 60 + 23, cell.cover.width - 65, 20);
//        cell.tagLabel.text = [tagStr stringByReplacingOccurrencesOfString:@"#" withString:@""];
        
//        cell.workName.font = [UIFont boldSystemFontOfSize:17];
//        CGSize nameSize = [self boundingRectWithSize:CGSizeMake(cell.cover.frame.size.width, 40) text:model.title font:cell.workName.font];
//
//        cell.workName.frame = CGRectMake(cell.cover.origin.x, cell.workTime.bottom + 12, cell.cover.width, nameSize.height);
//        cell.workName.text = model.title;
        
        cell.avatar.frame = CGRectMake(cell.cover.left, cell.cover.bottom + 5, avatarWidth, avatarWidth);
        [cell.avatar setImageWithURL:[NSURL URLWithString:model.headImageURL] placeholderImage:[UIImage imageNamed:@"plazz_placeholderImage"]];
        
        CGSize unameSize = [self boundingRectWithSize:CGSizeMake(100, 40) text:model.personName font:cell.userName.font];
        cell.userName.frame = CGRectMake(cell.avatar.right + 5, cell.avatar.top, unameSize.width,avatarWidth);
        cell.userName.text = model.personName;
        
        NSString *workTimeStr = [NSString stringWithFormat:@"%.2d'%.2d\"",model.duration.intValue / 60,model.duration.intValue % 60];
        cell.workTime.frame =  CGRectMake(cell.cover.left, cell.userName.top, cell.cover.width, avatarWidth);
        cell.workTime.text = workTimeStr;
        
        cell.tagImage.frame = CGRectMake(cell.cover.left, cell.avatar.bottom +  distans + 5, avatarWidth * 0.8, avatarWidth * 0.8);
        
        CGSize resonSize = [self boundingRectWithSize:CGSizeMake(cell.cover.width - cell.tagImage.width - 5, 2 * cell.workName.frame.size.height) text:model.reason font:cell.reconmendReson.font];
        cell.reconmendReson.frame = CGRectMake(cell.tagImage.right + 5, cell.tagImage.top, resonSize.width, resonSize.height);
        cell.reconmendReson.text = model.reason;
        
        cell.shareImage.frame = CGRectMake(cell.cover.right - 65, cell.reconmendReson.bottom + distans + 3, 25, 25);
        cell.shareTitle.frame = CGRectMake(cell.shareImage.right, cell.shareImage.top, 40, 25);
        
        cell.shareBtn.frame = CGRectMake(cell.shareImage.left, cell.shareImage.top, cell.shareImage.width + cell.shareTitle.width, 25);
        cell.shareBtn.tag = model.CinemeID.integerValue;
        [cell.shareBtn addTarget:self action:@selector(shareMenuShow) forControlEvents:UIControlEventTouchUpInside];
        
        cell.signButton.frame = CGRectMake(cell.cover.left, cell.shareBtn.bottom + 20, cell.cover.width, cell.cover.height / 7);
        [cell.signButton setTitle:@"每日签到" forState:UIControlStateNormal];
        [cell.signButton setTintColor:[UIColor whiteColor]];
        cell.signButton.backgroundColor = [UIColor blackColor];
        [cell.signButton addTarget:self action:@selector(signButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        if (self.isSigned == NO) {
            
        } else {
            cell.signButton.hidden = YES;
        }
        if (isSignClicked == YES) {
            cell.signButton.backgroundColor = [UIColor grayColor];
            [cell.signButton setTitle:@"已签到" forState: UIControlStateNormal];
        }
    }
    cell.playBlock = ^(NSString *uid, NSString *workid){
//        _playBtnBlock(uid,workid);
    };
    self.shareWorkId = model.CinemeID;
    self.shareWorkTitle = model.title;
    self.shareUserName = model.personName;
    self.shareCoverStr = model.worksImageURL;
    return cell;
}
- (void)signButtonClick:(UIButton *)sender
{
    isSignClicked = YES;
    sender.backgroundColor = [UIColor grayColor];
    [sender setTitle:@"已签到" forState: UIControlStateNormal];
    
}
#pragma mark --UICollectionViewDelegateFlowLayout

//定义每个Item 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    plaza_viewModel *model = _reconmendArray[indexPath.section];

    CGSize resonSize = [self boundingRectWithSize:CGSizeMake((self.frame.size.width *0.8  - 46) - avatarWidth * 0.7 - 5, MAXFLOAT) text:model.reason font:[UIFont systemFontOfSize:14]];
    CGFloat parameter;
    if (self.isSigned == YES) {
        parameter = 0;
    } else {
        parameter = (self.frame.size.width *0.8 - 46) / 7 + 20;
    }
//    if ([UIScreen mainScreen].bounds.size.width > 375) {
        return CGSizeMake(self.frame.size.width *0.8, self.frame.size.width * 0.8 + avatarWidth + 2 *distans + resonSize.height + 40 + parameter);
//    } else {
//       return CGSizeMake(self.frame.size.width *0.8, self.frame.size.width * 0.8 + resonSize.height + avatarWidth + 35 + 3 * distans + parameter);
//    }
}

//定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, self.frame.size.width *0.1, 0, self.frame.size.width *0.1);
}

#pragma mark --UICollectionViewDelegate

//UICollectionView被选中时调用的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    plaza_viewModel *model = _reconmendArray[indexPath.section];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"plazzGoToPlayer" object:model.CinemeID];
}

//返回这个UICollectionView是否可以被选择
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    _stopBlock();
}
- (CGSize)boundingRectWithSize:(CGSize)size text:(NSString *)text font:(UIFont *)font
{
    NSDictionary *attribute = @{NSFontAttributeName: font};
    
    CGSize retSize = [text boundingRectWithSize:size
                                        options:
NSStringDrawingTruncatesLastVisibleLine |
NSStringDrawingUsesLineFragmentOrigin |
NSStringDrawingUsesFontLeading
                                     attributes:attribute
                                        context:nil].size;
    
    return retSize;
}
- (void)shareMenuShow
{
    DownSheetModel *Model_2 = [[DownSheetModel alloc]init];
    Model_2.icon = @"UMS_wechat_timeline_icon@2x.png";
    Model_2.icon_on = @"UMS_wechat_timeline_icon@2x.png";
    Model_2.title = @"朋友圈";
    DownSheetModel *Model_6 = [[DownSheetModel alloc]init];
    Model_6.icon = @"UMS_wechat_icon@2x.png";
    Model_6.icon_on = @"UMS_wechat_icon@2x.png";
    Model_6.title = @"微信好友";
    DownSheetModel *Model_9 = [[DownSheetModel alloc] init];
    Model_9.icon = @"UMS_sina_icon.png";
    Model_9.icon_on = @"UMS_sina_icon.png";
    Model_9.title = @"新浪微博";
    NSArray *array = [NSArray array];
    if ([WXApi isWXAppInstalled]) {
        array = [NSArray arrayWithObjects:Model_2, Model_6, Model_9, nil];
    } else {
        array = [NSArray arrayWithObjects:Model_9, nil];
    }
    DownSheet *sheet = [[DownSheet alloc]initWithlist:array height:0];
    sheet.delegate = self;
    [sheet showInView:self];
}
-(void)didSelectIndex:(NSInteger)index
{
    switch (index) {
        case 0:
            [self shareToWXTimeline];
            break;
        case 1:
            [self shareToWXSession];
            break;
        case 2:
            [self shareToSina];
            break;
        default:
            break;
    }
}
- (void)shareToSina
{
    AppDelegate *myDelegate = [AppDelegate shareDelegate];
    WBAuthorizeRequest *authRequest = [WBAuthorizeRequest request];
    authRequest.redirectURI = kRedirectURI;
    authRequest.scope = @"all";
    
    WBMessageObject *message = [WBMessageObject message];
    message.text =[NSString stringWithFormat:@"《%@》来 #声音实验室# 听 %@ 的更多作品 %@",self.shareWorkTitle, self.shareUserName,[NSString stringWithFormat:@"http://www.pillele.cn/play.php?id=%@", self.shareWorkId]];
    
    UIImage *thumbImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:self.shareCoverStr]]];
    
    WBImageObject *object = [WBImageObject object];
    object.imageData = UIImageJPEGRepresentation(thumbImage, 1);
    message.imageObject = object;
    //
    WBSendMessageToWeiboRequest *request = [WBSendMessageToWeiboRequest requestWithMessage:message authInfo:authRequest access_token:myDelegate.wbtoken];
    request.userInfo = @{@"ShareMessageFrom": @"SendMessageToWeiboViewController",
                         @"Other_Info_1": [NSNumber numberWithInt:123],
                         @"Other_Info_2": @[@"obj1", @"obj2"],
                         @"Other_Info_3": @{@"key1": @"obj1", @"key2": @"obj2"}};
    [WeiboSDK sendRequest:request];
}
- (void)shareToWXTimeline
{
    WXMediaMessage *message = [WXMediaMessage message];
    message.title = [NSString stringWithFormat:@"%@｜声音实验室",self.shareWorkTitle];
    message.description = [NSString stringWithFormat:@"来声音实验室听 %@ 的更多作品",self.shareUserName];
    
    UIImage *thumbImage = [UIImage generatePhotoThumbnail:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:self.shareCoverStr]]]];
    
    [message setThumbImage:thumbImage];
    WXMusicObject *ext = [WXMusicObject object];
    ext.musicUrl = [NSString stringWithFormat:@"http://www.pillele.cn/play.php?id=%@", self.shareWorkId];//@"";
//    ext.musicDataUrl = _qiniuPlayUrlStr;
    message.mediaObject = ext;
    
    SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
    //    req.text = @"aaaaaaaaa"
    req.bText = NO;
    req.message = message;
    req.scene = 1;
    [WXApi sendReq:req];
    //    NSLog(@"%d",result);
}
- (void)shareToWXSession
{
    WXMediaMessage *message = [WXMediaMessage message];
    message.title = [NSString stringWithFormat:@"%@｜声音实验室",self.shareWorkTitle];
    message.description = [NSString stringWithFormat:@"来声音实验室听 %@ 的更多作品",self.shareUserName];
    UIImage *thumbImage = [UIImage generatePhotoThumbnail:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:self.shareCoverStr]]]];
    [message setThumbImage:thumbImage];
    WXMusicObject *ext = [WXMusicObject object];
    ext.musicUrl = [NSString stringWithFormat:@"http://www.pillele.cn/play.php?id=%@", self.shareWorkId];//@"";
//    ext.musicDataUrl = _qiniuPlayUrlStr;
    message.mediaObject = ext;
    
    SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    req.scene = 0;
    
    [WXApi sendReq:req];
}

@end
